package cn.wujiangbo.interceptor;

import cn.wujiangbo.annotation.IgnoreAuth;
import cn.wujiangbo.constants.ErrorCode;
import cn.wujiangbo.constants.SystemConstants;
import cn.wujiangbo.exception.MyException;
import cn.wujiangbo.util.MyTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * 校验登录的拦截器
 *
 * @Author 波波老师(weixin : javabobo0513)
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate redisTemplate;

    //前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 放行静态资源请求
        if (isStaticResourceRequest(request)) {
            return true;
        }

        if (!(handler instanceof HandlerMethod)) {
            //不是请求方法，则直接放行
            return true;
        }

        IgnoreAuth annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
        if (annotation != null) {
            //用IgnoreAuth注解标识的接口，直接放行
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        String methodName = method.getName();
        System.out.println("methodName=" + methodName);

        //1、从请求头中获取token
        String token = request.getHeader("token");
        if (!MyTools.hasLength(token)) {
            throw new MyException(ErrorCode.ERROR_CODE_1002.getMessage());
        }

        //根据token从Redis中获取到用户信息
        String userInfo = (String) redisTemplate.opsForValue().get(SystemConstants.LOGIN_TOKEN_KEY_APP + token);
        if (MyTools.hasLength(userInfo)) {
            //重新设置超时时间
            redisTemplate.opsForValue().set(SystemConstants.LOGIN_TOKEN_KEY_APP + token, userInfo, SystemConstants.LOGIN_TIME_OUT, TimeUnit.MINUTES);
            //放行
            return true;
        } else {
            //Redis中拿不到用户信息，抛异常
            throw new MyException(ErrorCode.ERROR_CODE_1002.getMessage());
        }
    }

    private boolean isStaticResourceRequest(HttpServletRequest request) {
        String uri = request.getRequestURI();
        // 根据你的静态资源路径配置来判断
        return uri.startsWith("/static/") || uri.startsWith("/images/") || uri.startsWith("/Resource/");
    }
}